<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { $fetch } from '@/settings/utils/fetch';
import { dialog } from '@/settings/components/dialog';
import { format, parseISO } from 'date-fns';

const listing = ref([]);
const pager = ref({});
const loading = ref(false);
const search = ref();

const refresh = async (page = 1) => {
  const { isSuccess, data } = await $fetch('/admin/email/history/getEmailHistoryList', {
    method: 'post',
    data: {
      pageNum: page,
      pageSize: 20,
    },
    loadingStatus: loading,
  });

  if (isSuccess) {
    listing.value = data.records;

    pager.value = {
      current: page,
      total: data.total,
    };
  }
}

const showUser = async (id: string) => {
  await dialog(() => import('./user-listing-window.vue'), {
    props: {
      id,
    },
  });
}

const showPreview = async (title: string, content: string) => {
  await dialog(() => import('./preview-window.vue'), {
    props: {
      title,
      content,
    },
  });
}

onMounted(() => {
  search.value.refresh('reset');
});
</script>

<template>
  <OpenPageSection>
    <OpenSearchTable sub-title="" button-text="$t('settings.view.subscription.user.history.button1')" :pager="pager" :data="listing" :loading="loading" @search="refresh" ref="search">
      <template #columns>
        <ATableColumn :title="$t('settings.view.subscription.user.history.column1')" data-index="emailTemplateTitle" />

        <ATableColumn :title="$t('settings.view.subscription.user.history.column2')">
          <template #cell="{ record }">
            {{ format(parseISO(record.createTime), 'yyyy-MM-dd HH:mm:ss') }}
          </template>
        </ATableColumn>

        <ATableColumn :title="$t('settings.view.subscription.user.history.column3')" data-index="createName" />

        <ATableColumn :title="$t('settings.view.subscription.user.history.column4')" :width="200">
          <template #cell="{ record }">
            <div class="button-actions">
              <AButton size="small" @click="showPreview(record.emailTemplateTitle, record.emailTemplateContent)">{{ $t('settings.action.preview') }}</AButton>
              <AButton size="small" @click="showUser(record.historyId)">{{ $t('settings.view.subscription.user.history.action') }}</AButton>
            </div>
          </template>
        </ATableColumn>
      </template>
    </OpenSearchTable>
  </OpenPageSection>
</template>

<style lang="scss" scoped>
</style>
